package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.constant.XcPlusConstant;
import com.xuecheng.base.exception.ResultEnum;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBasePageDTO;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.model.vo.CourseBaseInfoVo;
import com.xuecheng.content.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Resource
    private CourseMarketService courseMarketService;

    @Resource
    private CourseCategoryService courseCategoryService;
    @Resource
    private TeachplanService teachplanService;

    @Resource
    private TeachplanMediaService teachplanMediaService;

    @Resource
    private CourseTeacherService courseTeacherService;


    @Override
    public PageResult<CourseBase> queryCourseBasePage(PageParams pageParams,
                                                      CourseBasePageDTO courseBasePageDTO) {
        Long companyId = 1232141425L;//机构id写死，真实情况应该是从ThreadLocal中获取

        Long pageNo = pageParams.getPageNo();
        Long pageSize = pageParams.getPageSize();
        String courseName = courseBasePageDTO.getCourseName();
        String publishStatus = courseBasePageDTO.getPublishStatus();
        String auditStatus = courseBasePageDTO.getAuditStatus();

        Page<CourseBase> courseBasePage = new Page<>(pageNo, pageSize);

        lambdaQuery().like(!StringUtils.isEmpty(courseName),CourseBase::getName,courseName)
                .eq(!StringUtils.isEmpty(auditStatus),CourseBase::getAuditStatus,auditStatus)
                .eq(!StringUtils.isEmpty(publishStatus),CourseBase::getStatus,publishStatus)
                .eq(CourseBase::getCompanyId,companyId)//这一步应该要加上去，只能查询到自己上传的课程
                .page(courseBasePage);

        PageResult<CourseBase> pageResult = new PageResult<>();
        pageResult.setPageSize(pageSize);
        pageResult.setPage(pageNo);
        pageResult.setCounts(courseBasePage.getTotal());
        pageResult.setItems(courseBasePage.getRecords());

        return pageResult;
    }

    @Override
    @Transactional
    public CourseBaseInfoVo saveCourse(AddCourseDto addCourseDto) {

        //表单验证
        //checkData
        EditCourseDto editCourseDto = new EditCourseDto();
        BeanUtils.copyProperties(addCourseDto,editCourseDto);
        checkCourseData(editCourseDto);

        //保存基本信息
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto,courseBase);
        courseBase.setCompanyId(1232141425L);//机构id先写死
        courseBase.setAuditStatus(XcPlusConstant.COURSE_AUDIT_STATUS_FAIL);
        courseBase.setCreateDate(LocalDateTime.now());
        courseBase.setCreatePeople("大A老师");
        courseBase.setStatus(XcPlusConstant.COURSE_AUDIT_STATUS_NOT_SUBMITTED);
        save(courseBase);
        //保存营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        courseMarket.setId(courseBase.getId());//课程id
        courseMarketService.save(courseMarket);

        //查询课程信息并返回
        CourseBase courseBaseVo = getById(courseBase.getId());
        CourseMarket courseMarketVo = courseMarketService.getById(courseMarket.getId());

        CourseBaseInfoVo courseBaseInfoVo = new CourseBaseInfoVo();
        BeanUtils.copyProperties(courseBaseVo,courseBaseInfoVo);
        BeanUtils.copyProperties(courseMarketVo,courseBaseInfoVo);

        //大分类和小分类的名称
        courseBaseInfoVo.setMtName(courseCategoryService.getById(courseBaseInfoVo.getMt()).getName());
        courseBaseInfoVo.setStName(courseCategoryService.getById(courseBaseInfoVo.getSt()).getName());

        return courseBaseInfoVo;

    }


    @Override
    public CourseBaseInfoVo queryCourseById(Long courseId) {
        CourseBase courseBaseVo = getById(courseId);
        CourseMarket courseMarketVo = courseMarketService.getById(courseId);
        CourseBaseInfoVo courseBaseInfoVo = new CourseBaseInfoVo();
        BeanUtils.copyProperties(courseBaseVo,courseBaseInfoVo);
        BeanUtils.copyProperties(courseMarketVo,courseBaseInfoVo);


        //大分类和小分类的名称
        courseBaseInfoVo.setMtName(courseCategoryService.getById(courseBaseInfoVo.getMt()).getName());
        courseBaseInfoVo.setStName(courseCategoryService.getById(courseBaseInfoVo.getSt()).getName());

        return courseBaseInfoVo;
    }

    @Override
    @Transactional
    public CourseBaseInfoVo updateCourse(EditCourseDto editCourseDto) {

        //更新最好也要做表单验证
        checkCourseData(editCourseDto);

        //机构只能编辑自己上传过的课程
        Long companyId = 1232141425L;//这个值一般会从ThreadLocal中取
        if (!getById(editCourseDto.getId()).getCompanyId().equals(companyId)) {
            throw new XueChengPlusException("只能修改本机构的课程");
        }

        //更新两张表
        CourseBase courseBase = new CourseBase();
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseBase);
        BeanUtils.copyProperties(editCourseDto,courseMarket);

        courseBase.setChangePeople("大A");
        courseBase.setChangeDate(LocalDateTime.now());
        updateById(courseBase);//更新基本信息表

        courseMarketService.updateById(courseMarket);//更新营销表
        return queryCourseById(editCourseDto.getId());

    }

    @Override
    @Transactional
    public void deleteCourse(Long courseId) {


        CourseBase courseBase = getById(courseId);
        if (!courseBase.getAuditStatus().equals(XcPlusConstant.COURSE_AUDIT_STATUS_NOT_SUBMITTED)) {
            //不是未提交的状态
            throw new XueChengPlusException("课程已提交，暂时无法删除");

        }
        //删除多张表的信息
        //course_base表
        removeById(courseId);
        //删除营销表信息
        courseMarketService.removeById(courseId);
        //删除课程计划信息
        teachplanService.remove(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId,courseId));
        //删除media表信息
        teachplanMediaService.remove(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getCourseId,courseId));
        //删除教师信息
        courseTeacherService.remove(new LambdaQueryWrapper<CourseTeacher>().eq(CourseTeacher::getCourseId,courseId));

    }



    /**
     * 专门做表单验证的方法
     * @param editCourseDto
     */
    private void checkCourseData(EditCourseDto editCourseDto) {
        String name = editCourseDto.getName();
        if (StringUtils.isEmpty(name)){
            throw new XueChengPlusException(ResultEnum.COURSE_NAME_EMPTY);
        }
        //课程名称不能重复,得看是保存还是更新
        CourseBase courseBaseByName = lambdaQuery().eq(CourseBase::getName, name).one();
        if (editCourseDto.getId()==null){
            //保存
            if (courseBaseByName!=null){
                throw new XueChengPlusException("课程名称不能重复");
            }
        }else {
            //更新，所更改之后的课程名称不能和其它名称相同
            CourseBase courseBase = getById(editCourseDto.getId());
            //courseBaseByName不是null，而且其名称和原来的名称不同，证明你修改的这个课程名称和其它有冲突
            if (courseBaseByName!=null&&!courseBaseByName.getName().equals(courseBase.getName())){
                throw new XueChengPlusException("课程名称不能重复");
            }


        }



        //分类不能为空
        String mt = editCourseDto.getMt();
        String st = editCourseDto.getSt();
        if (StringUtils.isEmpty(mt)||StringUtils.isEmpty(st)){
            throw new XueChengPlusException(ResultEnum.COURSE_CATEGORY_EMPTY);
        }
        //等级不能为空
        String grade = editCourseDto.getGrade();
        if (StringUtils.isEmpty(grade)){
            throw new XueChengPlusException(ResultEnum.COURSE_GRADE_EMPTY);
        }
        //适用人群不能为空
        String users = editCourseDto.getUsers();
        if (StringUtils.isEmpty(users)){
            throw new XueChengPlusException(ResultEnum.COURSE_USER_EMPTY);
        }

        //收费规则不能为空
        String charge = editCourseDto.getCharge();
        if (StringUtils.isEmpty(charge)){
            throw new XueChengPlusException(ResultEnum.COURSE_CHARGE_EMPTY);
        }

        //收费模式下并且费用不能小于0
        Float price = editCourseDto.getPrice();
        Float originalPrice = editCourseDto.getOriginalPrice();
        if (XcPlusConstant.COURSE_COST_CHARGE.equals(charge)&&(price<=0||originalPrice<=0)){
            throw new XueChengPlusException(ResultEnum.COURSE_CHARGE_ERROR);
        }

    }

}
